package com.plian.Tools;

import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.SM2;
import org.bouncycastle.crypto.engines.SM2Engine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.DigestUtils;

import java.util.Map;
import java.util.TreeMap;

public class SmUtils {

    private static Logger logger = LoggerFactory.getLogger(SmUtils.class);

    private static final SM2Engine.Mode DIGEST = SM2Engine.Mode.C1C3C2;

    public static String genSign(Map<String, String> map, String secret) {
        Map<String, String> sMap = sortByKey(map);
        StringBuffer buffer = new StringBuffer(secret);
        for (Map.Entry<String, String> itm : sMap.entrySet()) {
            buffer.append(itm.getKey()).append(itm.getValue());
        }
        buffer.append(secret);
        try {
            String upperCase = (DigestUtils.md5DigestAsHex(buffer.toString().getBytes("utf-8")).toUpperCase());
            return upperCase;
        } catch (Exception e) {
            logger.error(e.toString());
        }
        return null;
    }

    private static Map<String, String> sortByKey(Map<String, String> map){
        //创建一个带有比较器的TreeMap
        Map<String, String> treeMap = new TreeMap<>(String::compareTo);
        //将你的map传入treeMap
        treeMap.putAll(map);
        return treeMap;
    }

    /**
     * sm2 解密
     * @param data
     * @param privateKey
     * @return
     */
    public static String decryptSm2(String data, String privateKey) {
        SM2 sm2 = SmUtil.sm2(privateKey, null);
        return sm2.decryptStr(data, KeyType.PrivateKey);
    }

    /**
     * sm2 加密
     * @param data
     * @param publicKey
     * @return
     */
    public static String encryptSm2(String data, String publicKey) {
        SM2 sm2 = SmUtil.sm2(null, publicKey);
        return sm2.encryptHex(data, KeyType.PublicKey);
    }

}
